import { Button } from 'antd';
import { useReducer } from 'react';

interface State {
  count: number;
}

type CounterAction = { type: 'reset' } | { type: 'setCount'; value: State['count'] };

const initialState: State = { count: 0 };

function stateReducer(state: State, action: CounterAction): State {
  switch (action.type) {
    case 'reset':
      return initialState;
    case 'setCount':
      return { ...state, count: action.value };
    default:
      throw new Error('unknown action');
  }
}

export default function Demo1() {
  const [state, dispatch] = useReducer(stateReducer, initialState);

  const addFive = () => {
    dispatch({ type: 'setCount', value: state.count + 5 });
  };

  const reset = () => {
    dispatch({ type: 'reset' });
  };

  return (
    <div>
      <h1>useReduce和ts类型练习</h1>
      <h1>欢迎来到我的计数器</h1>
      <p>计数：{state.count}</p>
      <Button type="primary" onClick={addFive}>
        加5
      </Button>
      <Button onClick={reset}>重置</Button>
    </div>
  );
}
